<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>医疗服务预约 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style>
        body {
            padding: 16px;
            background: #f5f7fa;
            height: 100vh;
            overflow: hidden;
        }
        .appointment-toolbar {
            margin-bottom: 12px;
            padding: 12px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .layui-table th, .layui-table td {
            text-align: center;
            padding: 8px 12px;
        }
        .layui-table thead tr {
            background-color: #f8f9fa;
        }
        .layui-form-label {
            width: 100px;
        }
        .layui-input-block {
            margin-left: 130px;
        }
        .layui-table-cell{
            height:auto;
            line-height: 30px;
        }
        .service-type-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: white;
        }
        .service-therapy {
            background-color: #1E9FFF;
        }
        .service-consultation {
            background-color: #5FB878;
        }
        .layui-table-cell{
            height:auto;
        }
    </style>
</head>
<body>
<div class="layui-card">
    <div class="layui-card-header" style="font-size:1.2em;font-weight:bold;"><i class="layui-icon layui-icon-date" style="color:#1E9FFF;"></i> 医疗服务预约</div>
    <div class="layui-card-body">
        <!-- 统计信息 -->
        <div style="display: flex; gap: 16px; margin-bottom: 16px;">
            <div class="layui-card" style="margin-bottom: 0; min-width: 120px;">
                <div class="layui-card-body" style="text-align: center; padding: 5px;">
                    <div style="font-size: 20px; color: #1E9FFF; font-weight: bold;" id="totalServices">0</div>
                    <div style="color: #666; font-size: 16px;">可预约服务</div>
                </div>
            </div>
            <div class="layui-card" style="margin-bottom: 0; min-width: 120px;">
                <div class="layui-card-body" style="text-align: center; padding: 5px;">
                    <div style="font-size: 20px; color: #5FB878; font-weight: bold;" id="totalDoctors">0</div>
                    <div style="color: #666; font-size: 16px;">医生数量</div>
                </div>
            </div>
        </div>
        <!-- 搜索表单 -->
        <form class="layui-form appointment-toolbar" id="searchForm">
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 90px;">服务类型</label>
                <div class="layui-input-inline" style="width: 160px;">
                    <select name="serviceType" id="serviceTypeSelect">
                        <option value="">全部类型</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <input type="text" name="doctorName" placeholder="医生姓名" class="layui-input" style="width: 150px;">
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 90px;">今日可预约</label>
                <div class="layui-input-inline" style="width: 120px;">
                    <select name="canAppointToday" id="canAppointTodaySelect">
                        <option value="">全部</option>
                        <option value="1">可预约</option>
                        <option value="0">不可预约</option>
                    </select>
                </div>
            </div>
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="search"><i class="layui-icon layui-icon-search"></i> 查询</button>
            <button class="layui-btn layui-btn-primary" type="reset"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
        </form>
        <!-- 服务预约表格 -->
        <div style="background: #fff; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <table class="layui-table" id="serviceTable" lay-filter="serviceTableFilter"></table>
        </div>
        <!-- 操作栏模板 -->
        <script type="text/html" id="tableBar">
            <button class="layui-btn layui-btn-primary layui-btn-xs btn-detail" lay-event="detail">详情</button>
            <button class="layui-btn layui-btn-normal layui-btn-xs btn-appoint" lay-event="appoint">预约</button>
        </script>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js"></script>
<script>
layui.use(['table', 'form', 'layer', 'jquery'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.jquery;

    var serviceTypes = [];
    var doctors = [];
    var serviceData = [];

    // 全局设置ajax请求头
    $.ajaxSetup({
        beforeSend: function(xhr) {
            const data = JSON.parse(localStorage.getItem('user'));
            //输出token
            console.log(data.token);
            if (data.token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
            }
        }
    });

    // 异步加载服务类型和医生数据
    function loadMedicalData() {
        $.get('/medical/services', function(res1) {
            if(res1.code === 0 && Array.isArray(res1.data)) {
                serviceTypes = res1.data;
                // 渲染服务类型下拉框
                var $select = $('#serviceTypeSelect');
                $select.empty();
                $select.append('<option value="">全部类型</option>');
                serviceTypes.forEach(function(st) {
                    $select.append('<option value="'+st.serviceType+'">'+st.serviceName+'</option>');
                });
                form.render('select');
                $.get('/medical/doctors', function(res2) {
                    if(res2.code === 0 && Array.isArray(res2.data)) {
                        doctors = res2.data;
                        // 组装表格数据
                        serviceData = doctors.map(function(doc) {
                            var st = serviceTypes.find(function(s) { return s.serviceType === doc.serviceType; });
                            return {
                                doctor_id: doc.doctorId,
                                doctorName: doc.doctorName,
                                avatar_url: doc.avatarUrl,
                                phone: doc.phone,
                                service_type: doc.serviceType,
                                serviceName: st ? st.serviceName : '',
                                service_description: st ? st.serviceDescription : '',
                                price: st ? st.price : '',
                                duration: st ? st.duration : '',
                                location: st ? st.location : '',
                                work_days: doc.workDays,
                                work_time_slots: doc.workTimeSlots,
                                profile: doc.profile
                            };
                        });
                        // 统计信息
                        $('#totalServices').text(serviceTypes.length);
                        $('#totalDoctors').text(doctors.length);
                        // 渲染表格
                        table.reload('serviceTable', {data: serviceData});
                    }
                });
            }
        });
    }

    // 获取今天是星期几（1-7，1为周一，7为周日）
    function getTodayWeekNum() {
        var jsDay = new Date().getDay();
        return jsDay === 0 ? 7 : jsDay;
    }
    // 判断医生今天是否可预约
    function canAppointToday(doctor) {
        var today = getTodayWeekNum();
        var workDays = doctor.work_days.split(',').map(Number);
        return workDays.includes(today);
    }

    // 初始化表格（先空数据，后续reload）
    table.render({
        elem: '#serviceTable',
        data: [],
        page: false,
        cols: [[
            { field: 'doctorName', title: '医生', minWidth: 70, align: 'center' },
            { field: 'phone', title: '联系电话', minWidth: 120, align: 'center' },
            { field: 'serviceName', title: '服务类型', minWidth: 160, align: 'center', templet: function(d){
                var desc = d.service_description ? d.service_description.replace(/"/g,'&quot;') : '';
                return '<span class="service-type-badge '+(d.service_type===1?'service-therapy':'service-consultation')+'" title="'+desc+'">'+d.serviceName+'</span>';
            } },
            { field: 'work_days', title: '工作日(星期)', minWidth: 100, align: 'center', templet: function(d) { return d.work_days.split(',').map(function(n) { return '一二三四五六日'[parseInt(n)-1]; }).join('、'); } },
            { field: 'work_time_slots', title: '可预约时间段', minWidth: 250, align: 'center', templet: function(d) { return d.work_time_slots.split(',').join('、'); } },
            { field: 'location', title: '地点', minWidth: 180, align: 'center' },
            { field: 'duration', title: '时长(分钟)', minWidth: 40, align: 'center' },
            { field: 'canAppointToday', title: '今日可预约', minWidth: 80, align: 'center', templet: function(d) {
                return canAppointToday(d) ? '<span style="color:green;">可预约</span>' : '<span style="color:#ccc;">不可预约</span>';
            }},
            { title: '操作', minWidth: 140, align: 'center', toolbar: '#tableBar' }
        ]],
        skin: 'line',
        even: true
    });

    // 预约弹窗表单HTML
    var appointDialogHtml = `
        <form class="layui-form" id="appointForm" style="padding:24px 18px 0 18px;max-width:420px;">
            <div class="layui-form-item">
                <label class="layui-form-label">服务类型</label>
                <div class="layui-input-block">
                    <input type="text" id="appointServiceType" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">医生</label>
                <div class="layui-input-block">
                    <input type="text" id="appointDoctorName" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">联系电话</label>
                <div class="layui-input-block">
                    <input type="text" id="appointPhone" class="layui-input" readonly>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">预约日期</label>
                <div class="layui-input-block">
                    <input type="text" name="appointDate" id="appointDate" class="layui-input" placeholder="请选择日期" readonly required>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">时间段</label>
                <div class="layui-input-block">
                    <select name="appointTimeSlot" id="appointTimeSlot" required>
                        <option value="">请选择时间段</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <input type="text" name="remark" class="layui-input" maxlength="100" placeholder="可选">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align:right;">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="submitAppoint">提交预约</button>
                </div>
            </div>
        </form>
    `;

    // 预约/详情按钮事件
    table.on('tool(serviceTableFilter)', function(obj) {
        if (obj.event === 'appoint') {
            if (!canAppointToday(obj.data)) {
                layer.msg('该医生今天不可预约', {icon: 0});
                return;
            }
            var d = obj.data;
            window.currentAppointDoctor = d;
            // 弹窗
            layer.open({
                type: 1,
                title: '预约服务',
                area: ['440px','auto'],
                shadeClose: true,
                content: appointDialogHtml,
                success: function(layero, idx) {
                    // 自动填充
                    $('#appointServiceType').val(d.serviceName);
                    $('#appointDoctorName').val(d.doctorName);
                    $('#appointPhone').val(d.phone);
                    // 日期选择器，仅允许选择医生工作日
                    layui.laydate.render({
                        elem: '#appointDate',
                        type: 'date',
                        min: 0,
                        calendar: true,
                        done: function(value, date) {
                            // 选择日期后刷新时间段
                            var $slot = $('#appointTimeSlot');
                            $slot.empty().append('<option value="">请选择时间段</option>');
                            if (d.work_time_slots) {
                                d.work_time_slots.split(',').forEach(function(ts) {
                                    $slot.append('<option value="'+ts+'">'+ts+'</option>');
                                });
                            }
                            form.render('select');
                        },
                        ready: function(date) {
                            setTimeout(function() {
                                $(".layui-laydate-content td").each(function() {
                                    var day = new Date($(this).attr('lay-ymd')).getDay();
                                    var week = day === 0 ? 7 : day;
                                    var workDays = d.work_days.split(',').map(Number);
                                    if (workDays.indexOf(week) === -1) {
                                        $(this).addClass('layui-disabled').css('color', '#ccc');
                                    }
                                });
                            }, 10);
                        },
                        change: function(value, date, endDate) {
                            setTimeout(function() {
                                $(".layui-laydate-content td").each(function() {
                                    var day = new Date($(this).attr('lay-ymd')).getDay();
                                    var week = day === 0 ? 7 : day;
                                    var workDays = d.work_days.split(',').map(Number);
                                    if (workDays.indexOf(week) === -1) {
                                        $(this).addClass('layui-disabled').css('color', '#ccc');
                                    }
                                });
                            }, 10);
                        }
                    });
                    // 初始化时间段
                    $('#appointTimeSlot').empty().append('<option value="">请选择时间段</option>');
                    if (d.work_time_slots) {
                        d.work_time_slots.split(',').forEach(function(ts) {
                            $('#appointTimeSlot').append('<option value="'+ts+'">'+ts+'</option>');
                        });
                    }
                    form.render('select');
                },
                end: function() {
                    // 关闭弹窗时重置表单
                    $('#appointForm')[0] && $('#appointForm')[0].reset();
                }
            });
        } else if (obj.event === 'detail') {
            var d = obj.data;
            var workDays = d.work_days.split(',').map(function(n){return '一二三四五六日'[parseInt(n)-1];}).join('、');
            var timeSlots = d.work_time_slots.split(',').join('、');
            var html = `
                <div style="display:flex;gap:48px;min-width:520px;max-width:680px;padding:32px 28px 28px 28px;">
                    <div style="flex:0 0 140px;text-align:center;">
                        <img src="${d.avatar_url?d.avatar_url:'../images/default_picture.png'}" style="width:112px;height:112px;border-radius:50%;border:2px solid #e6e6e6;object-fit:cover;box-shadow:0 2px 8px #eee;">
                        <div style="margin-top:20px;font-size:1.18em;font-weight:bold;">${d.doctorName}</div>
                        <div style="color:#888;font-size:1em;margin-top:8px;">${d.phone||''}</div>
                    </div>
                    <div style="flex:1;min-width:260px;">
                        <div style="margin-bottom:20px;">
                            <span class="service-type-badge ${(d.service_type===1?'service-therapy':'service-consultation')}" style="font-size:1.15em;vertical-align:middle;">${d.serviceName}</span>
                            <span style="color:#e74c3c;font-size:1.28em;font-weight:bold;margin-left:22px;vertical-align:middle;">${d.price ? '¥'+parseFloat(d.price).toFixed(2) : ''}</span>
                        </div>
                        <div style="margin-bottom:18px;color:#666;line-height:1.9;"><b>服务描述：</b>${d.service_description||'无'}</div>
                        <div style="margin-bottom:18px;color:#666;line-height:1.9;"><b>医生简介：</b>${d.profile||'无'}</div>
                        <div style="display:flex;flex-wrap:wrap;gap:18px 38px;margin-top:18px;font-size:1.05em;line-height:2.1;">
                            <div><b>工作日：</b>${workDays}</div>
                            <div><b>时间段：</b>${timeSlots}</div>
                            <div><b>地点：</b>${d.location}</div>
                            <div><b>时长：</b>${d.duration} 分钟</div>
                        </div>
                        <div style='text-align:right;margin-top:32px;'>
                            <button class="layui-btn layui-btn-normal" id="popupAppointBtn" lay-event="appoint">预约</button>
                        </div>
                    </div>
                </div>
            `;
            layer.open({
                type: 1,
                title: '服务详情',
                area: ['680px','auto'],
                shadeClose: true,
                content: html,
                success: function(layero, idx) {
                    layero.find('#popupAppointBtn').on('click', function(){
                        if (!canAppointToday(obj.data)) {
                            layer.msg('该医生今天不可预约', {icon: 0});
                            return;
                        }else {
                            layer.open({
                                type: 1,
                                title: '预约服务',
                                area: ['440px', 'auto'],
                                shadeClose: true,
                                content: appointDialogHtml,
                                success: function (layero, idx) {
                                    // 自动填充
                                    $('#appointServiceType').val(d.serviceName);
                                    $('#appointDoctorName').val(d.doctorName);
                                    $('#appointPhone').val(d.phone);
                                    // 日期选择器，仅允许选择医生工作日
                                    layui.laydate.render({
                                        elem: '#appointDate',
                                        type: 'date',
                                        min: 0,
                                        calendar: true,
                                        done: function (value, date) {
                                            // 选择日期后刷新时间段
                                            var $slot = $('#appointTimeSlot');
                                            $slot.empty().append('<option value="">请选择时间段</option>');
                                            if (d.work_time_slots) {
                                                d.work_time_slots.split(',').forEach(function (ts) {
                                                    $slot.append('<option value="' + ts + '">' + ts + '</option>');
                                                });
                                            }
                                            form.render('select');
                                        },
                                        ready: function (date) {
                                            setTimeout(function () {
                                                $(".layui-laydate-content td").each(function () {
                                                    var day = new Date($(this).attr('lay-ymd')).getDay();
                                                    var week = day === 0 ? 7 : day;
                                                    var workDays = d.work_days.split(',').map(Number);
                                                    if (workDays.indexOf(week) === -1) {
                                                        $(this).addClass('layui-disabled').css('color', '#ccc');
                                                    }
                                                });
                                            }, 10);
                                        },
                                        change: function (value, date, endDate) {
                                            setTimeout(function () {
                                                $(".layui-laydate-content td").each(function () {
                                                    var day = new Date($(this).attr('lay-ymd')).getDay();
                                                    var week = day === 0 ? 7 : day;
                                                    var workDays = d.work_days.split(',').map(Number);
                                                    if (workDays.indexOf(week) === -1) {
                                                        $(this).addClass('layui-disabled').css('color', '#ccc');
                                                    }
                                                });
                                            }, 10);
                                        }
                                    });
                                    // 初始化时间段
                                    $('#appointTimeSlot').empty().append('<option value="">请选择时间段</option>');
                                    if (d.work_time_slots) {
                                        d.work_time_slots.split(',').forEach(function (ts) {
                                            $('#appointTimeSlot').append('<option value="' + ts + '">' + ts + '</option>');
                                        });
                                    }
                                    form.render('select');
                                },
                                end: function () {
                                    // 关闭弹窗时重置表单
                                    $('#appointForm')[0] && $('#appointForm')[0].reset();
                                }
                            });
                        }
                    });
                }
            });
        }
    });

    // 搜索功能
    form.on('submit(search)', function(data) {
        var field = data.field;
        var filtered = serviceData.filter(function(item) {
            var match = true;
            if(field.serviceType && String(item.service_type) !== String(field.serviceType)) match = false;
            if(field.doctorName && item.doctorName.indexOf(field.doctorName) === -1) match = false;
            if(field.canAppointToday === '1' && !canAppointToday(item)) match = false;
            if(field.canAppointToday === '0' && canAppointToday(item)) match = false;
            return match;
        });
        table.reload('serviceTable', {data: filtered});
        return false;
    });
    // 重置
    $(document).on('click', '.layui-btn-primary[type="reset"]', function () {
        $('#searchForm')[0].reset();
        form.render();
        table.reload('serviceTable', {data: serviceData});
        return false;
    });

    // 预约表单提交
    form.on('submit(submitAppoint)', function(data) {
        var field = data.field;
        if (!field.appointDate) {
            layer.msg('请选择预约日期', {icon: 2});
            return false;
        }
        if (!field.appointTimeSlot) {
            layer.msg('请选择时间段', {icon: 2});
            return false;
        }
        var $btn = $(data.elem);
        $btn.prop('disabled', true).addClass('layui-btn-disabled');
        // 先校验是否为小区居民
        var userStr = localStorage.getItem('user');
        if (!userStr) {
            layer.msg('请先登录', {icon: 2});
            $btn.prop('disabled', false).removeClass('layui-btn-disabled');
            return false;
        }
        var user = JSON.parse(userStr);
        var userId = user.user.userId;
        if (!userId) {
            layer.msg('用户信息不完整，请重新登录', {icon: 2});
            $btn.prop('disabled', false).removeClass('layui-btn-disabled');
            return false;
        }
        // 查询居民ID
        $.ajax({
            url: '/resident/getByUserId',
            type: 'GET',
            data: { userId: userId },
            success: function(res) {
                if (res.code !== 0 || !res.data || !res.data.residentId) {
                    layer.msg('你还没有被注册成小区居民不能预约', {icon: 2});
                    $btn.prop('disabled', false).removeClass('layui-btn-disabled');
                    return;
                }
                var residentId = res.data.residentId;
                // 组装提交数据
                var postData = {
                    serviceType: window.currentAppointDoctor.service_type,
                    doctorName: $('#appointDoctorName').val(),
                    phone: $('#appointPhone').val(),
                    appointmentDate: field.appointDate,
                    timeSlot: field.appointTimeSlot,
                    remark: field.remark,
                    residentId: residentId
                };
                $.ajax({
                    url: '/medical/appointment/add',
                    type: 'POST',
                    data: JSON.stringify(postData),
                    contentType: 'application/json',
                    success: function(res) {
                        if(res.code === 0) {
                            layer.msg('预约提交成功！', {icon: 1});
                            layer.closeAll();
                        } else {
                            layer.msg(res.message || '预约提交失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，预约提交失败', {icon: 2});
                    },
                    complete: function() {
                        $btn.prop('disabled', false).removeClass('layui-btn-disabled');
                    }
                });
            },
            error: function() {
                layer.msg('校验居民身份失败，请稍后重试', {icon: 2});
                $btn.prop('disabled', false).removeClass('layui-btn-disabled');
            }
        });
        return false;
    });

    // 页面初始化时加载数据
    loadMedicalData();
});
</script>
</body>
</html> 